<?php
/**
 * Created by PhpStorm.
 * @author Sojo
 * Date: 2016/6/25
 * Time: 20:07
 */
namespace App\Http\Admin\User\Models;

use Framework\BaseClass\Http\Admin\Model;
use App\Eloquent\Admin\User as EloquentUser;

class User extends Model
{
    public function login($account, $password, $captcha = 0, $isRemember = false)
    {
        if (!\Auth::guard('admin')->attempt(['username' => $account, 'password' => $password]))
            xThrow(ERR_CLIENT_LOGIN_INFO);
    }

    public function getUserList()
    {
        $userList = EloquentUser::all();

        foreach ($userList as $user) {
            $user->register_time = $user->created_at->toDateString();
        }

        return $userList;
    }

    public function addUser($username, $email, $status)
    {
        $adminUser = EloquentUser::firstOrNew(['username' => $username]);
        if ($adminUser->id) xThrow(ERR_CLIENT_USER_ALREADY_EXISTS);
        $saveData = [
            'email'  => $email,
            'status' => $status
        ];

        return $this->saveUser($adminUser, $saveData);
    }

    public function updateUser($userId, $email, $status)
    {
        $adminUser = EloquentUser::find($userId);
        if (!$adminUser) xThrow(ERR_CLIENT_USER_NOT_EXIST);
        $saveData = [
            'email'  => $email,
            'status' => $status
        ];

        return $this->saveUser($adminUser, $saveData);
    }

    private function saveUser(EloquentUser $adminUser, array $saveData)
    {
        $adminUser->fill($saveData);
        return $adminUser->save();
    }

    public function delRole($userId)
    {
        $adminUser = EloquentUser::find($userId);
        if (!$adminUser) xThrow(ERR_CLIENT_USER_NOT_EXIST);
        return $adminUser->delete();
    }

    public function changePassword($userId, $oldPassword, $password)
    {
        $adminUser = EloquentUser::find($userId);
        if (!$adminUser) xThrow(ERR_LOGIC_NO_DATA_EXIST);
        if (!\Hash::check($oldPassword, $adminUser->password)) xThrow(ERR_CLIENT_USER_AUTH_INFO);
        $adminUser->password = $password;
        return $adminUser->save();
    }
}